package com.bifrost.service.impl;

import com.bifrost.authorization.manager.TokenManager;
import com.bifrost.authorization.manager.impl.RedisTokenManager;
import com.bifrost.common.constant.SessionConstant;
import com.bifrost.entity.Customer;
import com.bifrost.entity.CustomerType;
import com.bifrost.common.model.ResultModel;
import com.bifrost.repository.*;
import com.bifrost.service.*;
import com.bifrost.util.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @author rangf
 * @date 2018/1/25
 */
@Service
public class RegAndLogServiceImpl implements RegAndLogService {

    @Value("${jwt.token.expire}")
    private int EXPIRE;
    private static final Logger logger = LoggerFactory.getLogger(RegAndLogServiceImpl.class);
    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    @Qualifier("defaultTokenManager")
    TokenManager tokenManager;
    @Autowired
    CustomerAddressRepository customerAddressRepository;
    @Autowired
    CountryAreaRepository countryAreaRepository;
    @Autowired
    MediaService mediaService;
    @Autowired
    BonusPointsHistoryRepository bonusPointsHistoryRepository;
    @Autowired
    CustomerService customerService;
    @Autowired
    SmsService smsService;
    @Autowired
    StoreService storeService;
    @Autowired
    CustomerTypeRepository customerTypeRepository;

    /**
     * 会员注册
     *
     * @param customerPhone
     * @param message
     * @param customerPassword
     * @param request
     * @param response
     * @return
     */
    @Override
    public ResultModel regist(String customerPhone, String message, String customerPassword, HttpServletRequest request, HttpServletResponse response) {
        Customer isRegUser = customerService.findByCustomerPhone(customerPhone);
        if (isRegUser == null) {
            Boolean flag = smsService.checkMessage(customerPhone, message);
            if (Boolean.TRUE.equals(flag)) {
                Customer customer = new Customer();
                customer.setCustomerLastname(customerPhone);
                customer.setCustomerPhone(customerPhone);
                customer.setCustomerPassword(customerPassword);
                customer.setCreatedTimestamp(new Date());
                customer.setUpdatedTimestamp(new Date());
                customer.setActive(true);
                customer = customerService.saveWechatInfo(customer, request);
                logger.info("手机号为： " + customerPhone + "  的用户注册成功");
                if(execute(customer,request, response)) {
                    return ResultModel.ok();
                }
            }
            return ResultModel.error("验证码错误或已失效");
        }
        return ResultModel.error()
                .put("code", "0")
                .put("msg", "该手机号已被注册，请直接登录");
    }

    /**
     * @param request
     * @param response
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean loginAuto(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Object openId = request.getSession(true).getAttribute(SessionConstant.OPEN_ID);
        if (openId != null && !openId.toString().isEmpty()) {
            Customer customer = customerService.findByOpenId(openId.toString());
            if (customer != null) {
                customer.setLastLoginDate(new Date());
                customer = customerService.saveWechatInfo(customer, request);
                return execute(customer,request, response);
            } else {
                HttpSession session = request.getSession();
                String name =(String)session.getAttribute(SessionConstant.NICKNAME);
                Long storeId = (Long) session.getAttribute(SessionConstant.STORE_ID);
                customer = new Customer();
                customer.setCreatedTimestamp(new Date());
                customer.setCustomerLastname(name);
                customer.setCustomerPassword("e10adc3949ba59abbe56e057f20f883e");
                customer.setUpdatedTimestamp(new Date());
                customer.setMerchantStore(storeService.getMerchantStore(storeId));
                customer.setActive(true);
                CustomerType defaultType= customerTypeRepository.findFirstByTypeCodeAndMerchantId(CustomerType.DEFAULT_TYPE_CODE,storeId);
                if(defaultType==null){
                    defaultType= new CustomerType();
                    defaultType.setTypeCode(CustomerType.DEFAULT_TYPE_CODE);
                    defaultType.setMerchantId(storeId);
                    defaultType.setName(CustomerType.DEFAULT_TYPE_NAME);
                    defaultType.setDescription(CustomerType.DEFAULT_TYPE_NAME);
                    defaultType = customerTypeRepository.save(defaultType);
                }
                customer.setCustomerType(defaultType);
                customer = customerService.saveWechatInfo(customer, request);
                return execute(customer,request, response);
            }
        }
        return false;
    }

    /**
     * 密码登录
     *
     * @param customerPhone
     * @param customerPassword
     * @param response
     * @param request
     * @return
     */
    @Override
    public ResultModel loginWithPwd(String customerPhone, String customerPassword, HttpServletResponse response, HttpServletRequest request) {
        if (!StringUtils.isEmpty(customerPhone) && !StringUtils.isEmpty(customerPassword)) {
            Customer customer = customerService.findByCustomerPhone(customerPhone);
            if (customer != null) {
                if (customerPassword.equals(customer.getCustomerPassword())) {
                    String openId = customer.getOpenId();
                    if (StringUtils.isEmpty(openId)) {
                        customer = customerService.saveWechatInfo(customer, request);
                    }
                    if(execute(customer,request, response)) {
                        return ResultModel.ok();
                    }
                }
                return ResultModel.error("用户名或密码不正确");
            }
            return ResultModel.error("用户名或密码不正确");
        }
        return ResultModel.error("手机号码或密码不能为空");
    }

    /**
     * 验证码登录
     *
     * @param customerPhone
     * @param validateCode
     * @param response
     * @param request
     * @return
     */
    @Override
    public ResultModel loginWithCode(String customerPhone, String validateCode, HttpServletResponse response, HttpServletRequest request) {
        Customer customer = customerService.findByCustomerPhone(customerPhone);
        if (customer != null) {
            Boolean flag = smsService.checkMessage(customerPhone, validateCode);
            if (Boolean.TRUE.equals(flag)) {
                String openId = customer.getOpenId();
                if (StringUtils.isEmpty(openId)) {
                    customer = customerService.saveWechatInfo(customer, request);
                }
                if(execute(customer,request, response)) {
                    return ResultModel.ok();
                }
            }
            return ResultModel.error()
                    .put("code", "2")
                    .put("msg", "验证码错误");
        }
        return ResultModel.error()
                .put("code", "1")
                .put("msg", "该手机号码还未注册,请先注册");

    }

    /**
     * 注销
     *
     * @param customer
     * @param response
     * @return
     */
    @Override
    public ResultModel logout(Customer customer, HttpServletResponse response) {
        tokenManager.deleteToken(customer.getCustomerId());
        CookieUtils.clearCookie(response, "token");
        return ResultModel.ok("注销成功");
    }

    /**
     * 记录用户行为到服务端和客户端
     *
     * @param customer
     * @param request
     * @param response
     * @return
     */
    private boolean execute(Customer customer, HttpServletRequest request, HttpServletResponse response) {
        String token = null;
        try {
            token = tokenManager.createToken(customer.getCustomerId());
            CookieUtils.saveCookie(response, "token", token, EXPIRE * 24 * 3600);
            CookieUtils.saveCookie(response, "uid", customer.getCustomerId().toString(), EXPIRE * 24 * 3600);
            CookieUtils.saveCookie(response, "uname", customer.getCustomerLastname(), EXPIRE * 24 * 3600);
            CookieUtils.saveCookie(response, "avatar", customer.getMedia()==null?"":customer.getMedia().getUrl(), EXPIRE * 24 * 3600);
            CookieUtils.saveCookie(response,"store",customer.getMerchantStore().getMerchantId().toString(),EXPIRE * 24 * 3600);
            if(request!=null){
                request.getSession(true).setAttribute(SessionConstant.TOKEN,token);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
       return false;

    }
}
